import request from '../utils/request.js'
import config from '../config.js'
import mockPosts from '../mock/communityPosts.js'
import mockComments from '../mock/communityComments.js'

/**
 * 获取社区帖子列表
 * @param {Object} params 查询参数，如页码、标签等
 * @returns {Promise} Promise对象
 */
export const getCommunityPosts = (params = {}) => {
  return request({
    url: `${config.apiBaseUrl}/api/community/posts`,
    method: 'GET',
    data: params
  })
}

/**
 * 获取帖子详情
 * @param {String|Number} id 帖子ID
 * @returns {Promise} Promise对象
 */
export const getPostDetail = (id) => {
  return request({
    url: `${config.apiBaseUrl}/api/community/posts/${id}`,
    method: 'GET'
  })
}

/**
 * 发布帖子
 * @param {Object} post 帖子数据
 * @returns {Promise} Promise对象
 */
export const createPost = (post) => {
  // 处理图片数组，确保格式正确
  const postData = { ...post }
  
  // 如果有图片，转换为JSON字符串
  if (postData.images && postData.images.length > 0) {
    postData.images = JSON.stringify(postData.images)
  } else {
    postData.images = '[]'
  }
  
  return request({
    url: `${config.apiBaseUrl}/api/community/posts`,
    method: 'POST',
    data: postData
  })
}

/**
 * 点赞/取消点赞帖子
 * @param {String|Number} id 帖子ID
 * @param {Boolean} isLike 是否点赞
 * @returns {Promise} Promise对象
 */
export const likePost = (id, isLike) => {
  return request({
    url: `${config.apiBaseUrl}/api/community/posts/${id}/like`,
    method: 'PUT',
    data: { isLike }
  })
}

/**
 * 发表评论
 * @param {String|Number} postId 帖子ID
 * @param {Object} comment 评论数据
 * @returns {Promise} Promise对象
 */
export const createComment = (postId, comment) => {
  return request({
    url: `${config.apiBaseUrl}/api/community/posts/${postId}/comments`,
    method: 'POST',
    data: comment
  })
}

/**
 * 点赞/取消点赞评论
 * @param {String|Number} id 评论ID
 * @param {Boolean} isLike 是否点赞
 * @returns {Promise} Promise对象
 */
export const likeComment = (id, isLike) => {
  return request({
    url: `${config.apiBaseUrl}/api/community/comments/${id}/like`,
    method: 'PUT',
    data: { isLike }
  })
}

/**
 * 删除帖子
 * @param {String|Number} id 帖子ID
 * @returns {Promise} Promise对象
 */
export const deletePost = (id) => {
  return request({
    url: `${config.apiBaseUrl}/api/community/posts/${id}`,
    method: 'DELETE'
  })
}

/**
 * 删除评论
 * @param {String|Number} id 评论ID
 * @returns {Promise} Promise对象
 */
export const deleteComment = (id) => {
  return request({
    url: `${config.apiBaseUrl}/api/community/comments/${id}`,
    method: 'DELETE'
  })
}

export default {
  getCommunityPosts,
  getPostDetail,
  createPost,
  likePost,
  createComment,
  likeComment,
  deletePost,
  deleteComment
} 